// src/app/list/page.tsx (最终、最鲁棒的兼容版本)
import UserList from "@/components/UserList";
import PaginationControls from "@/components/PaginationControls";
import { User } from "@/types/user";
import React from "react";

const TOTAL_USERS = 10;
const DEFAULT_LIMIT = 5;

// 定义 Props 接口，但我们知道运行时可能会将其包装成 Promise
interface SearchParamsObject {
  page?: string;
  limit?: string;
}

// 适应运行时：将 searchParams 的类型定义为 Object 或 Promise<Object>
interface ListPageProps {
  searchParams: SearchParamsObject | Promise<SearchParamsObject>;
}

// 必须是 async 函数
export default async function UserListPage(props: ListPageProps) {
  // 核心修改：对 searchParams 进行 await，以满足严格的运行时检查
  // 无论它是 Promise 还是普通对象，await 都能安全处理。
  const searchParams = await props.searchParams;

  // 1. 安全解析和校验参数
  const currentPage = parseInt(searchParams?.page || "1", 10);
  const limit = parseInt(searchParams?.limit || `${DEFAULT_LIMIT}`, 10);

  const totalPages = Math.ceil(TOTAL_USERS / limit);
  const validatedPage = Math.max(1, Math.min(currentPage, totalPages));

  const start = (validatedPage - 1) * limit;

  const API_URL = `https://jsonplaceholder.typicode.com/users?_start=${start}&_limit=${limit}`;

  // 2. 数据获取 (强制禁用缓存以实现分页)
  const res = await fetch(API_URL, {
    cache: "no-store",
  });

  if (!res.ok) {
    throw new Error("Failed to fetch user list");
  }

  const users: User[] = await res.json();

  return (
    <div className="p-8 max-w-4xl mx-auto">
      <h1 className="text-4xl font-extrabold mb-8 text-center text-gray-800">
        用户列表与分页
      </h1>
      <UserList users={users} />
      <PaginationControls
        currentPage={validatedPage}
        totalPages={totalPages}
        limit={limit}
      />
    </div>
  );
}
